import tkinter as tk
from tkinter import ttk, filedialog
import os
import sys
from PIL import Image, ImageTk
import ttkbootstrap as ttkb
from services.import_service import ImportService
from tkinterdnd2 import DND_FILES, TkinterDnD
from utils import resource_path, log_debug, log_error, log_exception

class ImportView(ttkb.Frame, TkinterDnD.DnDWrapper):
    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.parent = parent
        self.import_service = ImportService()
        # 初始化DnD功能
        self.TkdndVersion = TkinterDnD._require(self)
        self.create_widgets()

    def create_widgets(self):
        # 创建拖拽区域框架
        drag_drop_frame = self

        # 拖拽区域（可点击）
        drop_frame = ttkb.LabelFrame(
            drag_drop_frame,
            text='拖拽文件至此或点击选择文件导入题库',
            bootstyle="info",
            padding=20,
            width=500,
            height=200,
            cursor="hand2"
        )
        drop_frame.pack(fill=tk.X, pady=10)
        drop_frame.pack_propagate(False)
        # 绑定点击事件
        drop_frame.bind("<Button-1>", lambda e: self.open_file_selector())

        # 支持的文件类型说明
        supported_types = ttkb.Label(
            drag_drop_frame,
            text="支持JSON, Excel, CSV, 包含PDF的ZIP压缩包",
            font=('SimHei', 10),
            bootstyle="info"
        )
        supported_types.pack(pady=10)

        # 创建包含图标和文本的框架（无边框）
        content_frame = ttkb.Frame(drop_frame)
        content_frame.pack(expand=True)
        # 确保内部框架不会阻止点击事件传播
        content_frame.bind("<Button-1>", lambda e: self.open_file_selector())

        # 创建内部框架用于居中显示图标和文字
        inner_frame = ttkb.Frame(content_frame)
        inner_frame.pack(expand=True)
        # 确保内部框架不会阻止点击事件传播
        inner_frame.bind("<Button-1>", lambda e: self.open_file_selector())

        # 添加图标
        icon_path = resource_path(os.path.join("icon", 'pick_file.png'))
        if os.path.exists(icon_path):
            pil_image = Image.open(icon_path)
            pil_image = pil_image.resize((60, 60), Image.LANCZOS)
            icon_image = ImageTk.PhotoImage(pil_image)
            icon_label = ttkb.Label(inner_frame, image=icon_image)
            icon_label.image = icon_image
            icon_label.pack(pady=10)
            icon_label.bind("<Button-1>", lambda e: self.open_file_selector())

        # 绑定拖拽事件
        # 确保框架支持DnD
        drop_frame.drop_target_register(DND_FILES)
        drop_frame.dnd_bind('<<Drop>>', self.on_drop)
        drop_frame.dnd_bind('<<DragEnter>>', lambda e: e.widget.focus_set())
        drop_frame.dnd_bind('<<DragOver>>', lambda e: e.widget.focus_set())

        # 添加进度条和状态标签
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttkb.Progressbar(
            drag_drop_frame,
            variable=self.progress_var,
            bootstyle="info",
            length=400
        )
        self.progress_bar.pack(pady=10)

        self.progress_label = ttkb.Label(
            drag_drop_frame,
            text="准备就绪",
            bootstyle="info"
        )
        self.progress_label.pack(pady=5)

        self.result_label = ttkb.Label(
            drag_drop_frame,
            text="",
            bootstyle="info"
        )
        self.result_label.pack(pady=5)

    def open_file_selector(self):
        """打开文件选择器"""
        file_path = filedialog.askopenfilename(
            title="选择题库文件",
            filetypes=[
                ("所有支持的文件", "*.json;*.xlsx;*.xls;*.csv;*.zip"),
                ("JSON文件", "*.json"),
                ("Excel文件", "*.xlsx;*.xls"),
                ("CSV文件", "*.csv"),
                ("ZIP压缩包", "*.zip")
            ]
        )
        if file_path:
            self.do_import(file_path)

    def on_drop(self, event):
        """处理拖拽文件事件"""
        try:
            # 获取拖拽的文件路径
            if hasattr(event, 'data'):
                files = self.parent.tk.splitlist(event.data)
            else:
                files = []

            if files:
                for file_path in files:
                    # 处理Windows路径格式
                    if file_path.startswith('file:///'):
                        file_path = file_path[8:].replace('/', '\\')
                    self.do_import(file_path)
        except Exception as e:
            log_exception(f"拖拽文件处理异常: {str(e)}")
            self.result_label.config(text=f"拖拽文件处理异常: {str(e)}")

    def do_import(self, file_path):
        """执行导入操作"""
        try:
            self.progress_var.set(0)
            self.progress_label.config(text=f"开始导入 {os.path.basename(file_path)}...")
            self.result_label.config(text="")

            # 使用导入服务处理文件
            success, result, imported_count, total, stats = self.import_service.process_unified_data(
                file_path,
                progress_var=self.progress_var,
                progress_label=self.progress_label,
                import_dialog=self
            )

            if success:
                self.progress_label.config(text="导入完成")
                
                # 确保result_frame已初始化并放置在进度条下方
                if not hasattr(self, 'result_frame') or self.result_frame is None:
                    self.result_frame = ttk.Frame(self)
                    self.result_frame.pack(fill=tk.BOTH, expand=True, pady=10)
                else:
                    # 清空之前的表格
                    for widget in self.result_frame.winfo_children():
                        widget.destroy()
                
                # 创建表格样式
                style = ttk.Style()
                style.configure("Treeview.Heading", font=('SimHei', 10, 'bold'))
                style.configure("Treeview", font=('SimHei', 10), borderwidth=1)
                style.layout("Treeview", [
                    ('Treeview.treearea', {'sticky': 'nswe'})
                ])

                # 创建表格
                table = ttk.Treeview(self.result_frame, columns=('题型', 'A类', 'B类', 'C类'), show='headings', height=6)

                # 设置列标题并居中
                table.heading('题型', text='题型', anchor='center')
                table.heading('A类', text='A类', anchor='center')
                table.heading('B类', text='B类', anchor='center')
                table.heading('C类', text='C类', anchor='center')

                # 设置列宽和居中
                table.column('题型', width=100, anchor='center')
                table.column('A类', width=100, anchor='center')
                table.column('B类', width=100, anchor='center')
                table.column('C类', width=100, anchor='center')

                # 添加表格边框
                table.configure(style="Treeview")
                
                # 添加数据
                # 单选题
                a_single = stats.get('single_choice_type_a', 0)
                b_single = stats.get('single_choice_type_b', 0)
                c_single = stats.get('single_choice_type_c', 0)
                table.insert('', 'end', values=('单选题', a_single, b_single, c_single))
                
                # 多选题
                a_multiple = stats.get('multiple_choice_type_a', 0)
                b_multiple = stats.get('multiple_choice_type_b', 0)
                c_multiple = stats.get('multiple_choice_type_c', 0)
                table.insert('', 'end', values=('多选题', a_multiple, b_multiple, c_multiple))
                
                # 添加分隔线
                table.insert('', 'end', values=('---', '---', '---', '---'))
                
                # 总计
                total_a = a_single + a_multiple
                total_b = b_single + b_multiple
                total_c = c_single + c_multiple
                table.insert('', 'end', values=('总计', total_a, total_b, total_c))
                
                # 显示表格
                table.pack(fill=tk.BOTH, expand=True)
                
                # 显示导入成功信息和统计数据
                total_single = stats.get('single_choice', 0)
                total_multiple = stats.get('multiple_choice', 0)
                total_image = stats.get('has_image', 0)
                elapsed_time = round(stats.get('elapsed_time', 0), 2)

                info_label = ttk.Label(self.result_frame, text=f"成功导入 {imported_count} 道题目，共 {total} 道题目")
                info_label.pack(pady=5)

                stats_label = ttk.Label(self.result_frame, text=f"其中：单选题 {total_single} 道，多选题 {total_multiple} 道，含图片题 {total_image} 道，耗时 {elapsed_time} 秒")
                stats_label.pack(pady=5)
            else:
                self.progress_label.config(text="导入失败")
                self.result_label.config(text=f"导入过程中出错: {result}")
                log_error(f"导入失败: {result}")
        except Exception as e:
            self.progress_label.config(text="导入失败")
            self.result_label.config(text=f"导入过程中发生异常: {str(e)}")
            log_exception(f"导入异常: {str(e)}")


# 确保中文显示正常
import matplotlib
matplotlib.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]

# 修复可能的导入问题
import sys
if hasattr(sys, 'frozen') and sys.frozen == 'windows_exe':
    # 如果是打包的exe文件
    import ctypes
    ctypes.windll.shcore.SetProcessDpiAwareness(1)